package org.bear.graph.base;

// 208. 实现 Trie (前缀树)
public class Trie {
    Trie[] children;
    boolean isEnd;

    public Trie() {
        children = new Trie[26];
        isEnd = false;
    }

    public void insert(String word) {
        if (word == null) {
            return;
        }
        if (word.isEmpty()) {
            return;
        }
        doInsert(word, 0, this);

    }

    private void doInsert(String word, int pos, Trie node) {
        if (pos < word.length()) {
            int hashPos = word.charAt(pos) - 'a';
            Trie trie = node.children[hashPos];
            if (trie == null) {
                trie = new Trie();
                node.children[hashPos] = trie;
            }
            if (pos+1 == word.length()) {
                trie.isEnd = true;
            }else {
                doInsert(word, pos+1, trie);
            }
        }
    }

    public boolean search(String word) {
        Trie node = this;
        for (int i = 0; i < word.length(); i++) {
            int hashPos = word.charAt(i) - 'a';
            if (node.children[hashPos] == null) {
                return false;
            }
            node = node.children[hashPos];
        }
        return node.isEnd;
    }

    public boolean startsWith(String prefix) {
        Trie node = this;
        for (int i = 0; i < prefix.length(); i++) {
            int hashPos = prefix.charAt(i) - 'a';
            if (node.children[hashPos] == null) {
                return false;
            }
            node = node.children[hashPos];
        }
        return true;
    }

    public static void main(String[] args) {
        Trie trie = new Trie();
        trie.insert("apple");
        trie.search("apple");
    }

}
